package com.example.demo.controller;


import com.example.demo.pojo.Message;
import com.example.demo.pojo.SigIn;
import com.example.demo.pojo.User;
import com.example.demo.server.UserServer;
import com.example.demo.utils.TokenTool;
import com.example.demo.utils.Tool;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;


/**
 * 用户的Controller接口 , 用于成立用户的信息
 *
 * @author 刘二朋
 * @date 2020-11-27 15:03
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户管理", description = "处理用户的信息 , 查询用户的信息 , 修改用户的信息")
@CrossOrigin(origins = "*")//解决跨域问题
public class UserController {

    //    指定装配一个 UserServer对象 , 用于操作用户的数据
    @Autowired
    private UserServer userServer;

    /**
     * 指定装配一个处理头像的AvaterService
     */
//    @Autowired
//    private AvaterServer avaterServer;


    /**
     * 用户注册接口 , 用于用户的注册
     *
     * @param user 客户端提交的数据
     * @return 返回 , 处理的结果 , 成功 , 还是失败
     */
    @PostMapping("/signUp")
    @ResponseBody
    @Operation(summary = "用户注册",
            description = "无需token",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "用户请求参数",
                    content = @Content(
                            mediaType = "application/json",
                            examples = @ExampleObject(
                                    value = "{" +
                                            "\"id\":\"13123456781\"," +
                                            "\"name\":\"小明\"," +
                                            "\"password\":\"88888888\"," +
                                            "}"
                            ))),
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "注册成功",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(
                                            value = "{\"code\":2000,\"message\":\"注册成功！\",\"data\":{\"user\":{\"id\":\"13123456781\",\"name\":\"小明\",\"avatar\":\"http://localhost:8080/admin_server/image/1.jpeg\"},\"token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIzIn0.C8BJb_bEFh0tO8lQy9z28RzHIbYOL3JQfBD8ZzHyFco\"}}"
                                    )
                            )),
            })
    public Message signUp(@RequestBody SigIn user) {
        System.out.println("得到客户端发送的请求 : " + user);
//        创建一个消息对象
        Message message = new Message();
//        创建用户是否存在 :
        User user2 = userServer.fromById(user.getId());
        if (user2 != null) {
            message.setErrorMessage("用户已存在，请登录！").setCode(3);
            return message;
        }
//        创建一个User对象 ,
        User user1 = new User();
        user1.setId(user.getId());
        user1.setName(user.getName());
        user1.setPassword(user.getPassword());
//        设置用户的头像
        //        设置图片的名字
        int i1 = new Random().nextInt(9);
//        设置头像
        user1.setAvater(Tool.Context + Tool.imagePath + Tool.images[i1]);

        User user3 = userServer.saveTheUser(user1);
        if (user3 == null) {
            message.setErrorMessage("注册失败，请重新注册！").setCode(4);
            return message;
        }
        System.out.println("用户保存成功");
//        把保存的用户 , 发送到客户端 , 创建用户对应的token
        String token = TokenTool.getToken(user3); //获取token
        System.out.println("注册时的用户信息 : " + user3);
        message.setSuccessMessage("注册成功！").put("token", token).put("user", user3);
        return message;
    }

    /**
     * 用户登录的接口 . 用于用户的登录 , 判断用户提交的账号与密码
     *
     * @param user 要进行操作的数据
     * @return 返回 , 操作的结果 , 对应的Token
     */
    @PostMapping("/login")
    @ResponseBody
    @Operation(summary = "用户登录",
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "登录成功",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(description = "data数据为：", value = "{\n" +
                                            "  \"code\": 2000,\n" +
                                            "  \"message\": \"登录成功！\",\n" +
                                            "  \"data\": {\n" +
                                            "    \"user\": {\n" +
                                            "      \"id\": 13123456781,\n" +
                                            "      \"name\": \"null\",\n" +
                                            "      \"password\": \"88888888\",\n" +
                                            "      \"avatar\": null\n" +
                                            "    },\n" +
                                            "  }\n" +
                                            "}")
                            )),
                    @ApiResponse(responseCode = "2001", description = "密码错误")
            })
    public Message login(@RequestBody SigIn user) {
//        创建一个消息对象
        Message message = new Message();
//        根据用户的账号 , 密码 , 来进行判断 , 该用户 , 是否可以进行登录的操作
        User byIdAndPassword = userServer.findByIdAndPassword(user.getId(), user.getPassword());
        if (byIdAndPassword == null) {
            message.setErrorMessage("登录失败 , 请检查 账号密码 , 是否正确");
            message.setCode(1);
        } else {
//            查询到了用户 , 把用户 , 返回到客户端 , 进行登录的操作
//            获取用户对应的Token信息 , 并把Token信息 , 一块带到客户端进行保存
            String token = TokenTool.getToken(byIdAndPassword); //获取token
            message.setSuccessMessage("登录成功！").put("token", token).put("user", byIdAndPassword);
        }
        return message;
    }

    /**
     * 搜索 搜索用户的接口 , 用于搜索用户 ,进行展示
     *
     * @param user 要进行操作的用户对象
     * @return 方法搜索到的用户
     */
    @PostMapping("/seekUser")
    @ResponseBody
    @Operation(summary = "搜索用户",
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "搜索成功 , 把用户返回到对应的客户端 , 进行展示",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(description = "data数据为：", value = "{\n" +
                                            "  \"code\": 2000,\n" +
                                            "  \"message\": \"搜索成功！\",\n" +
                                            "  \"data\": {\n" +
                                            "    \"user\": {\n" +
                                            "      \"id\": 13123456781,\n" +
                                            "      \"name\": \"张三\",\n" +
                                            "      \"password\": \"88888888\",\n" +
                                            "      \"avatar\": 头像\n" +
                                            "    },\n" +
                                            "  }\n" +
                                            "}")
                            )),
                    @ApiResponse(responseCode = "2001", description = "没有搜索到该用户")
            })
    public Message seekUser(@RequestBody SigIn user) {
//      创建一个消息对象 , 用于向服务端发送消息 ,
        Message message = new Message();
        System.out.println("搜索用户 , 得到的数据 :" + user);
//        通过用户的id  ,来查询用户
        User user1 = userServer.fromById(user.getId());
        if (user1 == null) {
            message.setErrorMessage("您搜索的用户不存在，请重新查询用户！").setCode(3);
            return message;
        }
//        用户存在 , 把用户 , 返回到对应的客户端
        message.setSuccessMessage("搜索成功").put("user", user1);
        return message;
    }

    /**
     * 修改昵称的接口
     *
     * @param user    要进行修改的昵称
     * @param request 要操作的用户
     * @return 返回操作的结果
     */
    @PostMapping("/reName")
    @ResponseBody
    @Operation(summary = "修改昵称",
            description = "需要token",
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "昵称修改成功",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(description = "data数据为：", value = "{\n" +
                                            "  \"code\": 2000,\n" +
                                            "  \"message\": \"修改成功！\",\n" +
                                            "  \"data\": {\n" +
                                            "    \"user\": {\n" +
                                            "      \"name\": \"张三\",\n" +
                                            "    },\n" +
                                            "  }\n" +
                                            "}")
                            )),
                    @ApiResponse(responseCode = "2001", description = "昵称修改失败")
            })
    public Message reName(@RequestBody SigIn user, HttpServletRequest request) {
        Message message = new Message();
        String tokenUserId = TokenTool.getTokenUserId(request);
//        修改用户的名字
        int i = userServer.updataNameInId(tokenUserId, user.getName());
        if (i == 0) {
//            修改失败
            message.setErrorMessage("昵称修改失败！").setCode(3);
            return message;
        }
        message.setSuccessMessage("昵称修改成功");
        return message;
    }

    /**
     * 修改密码的接口
     *
     * @param user    要进行修改的密码
     * @param request 要操作的用户
     * @return 返回操作的结果
     */
    @PostMapping("/rePass")
    @ResponseBody
    @Operation(summary = "修改密码",
            description = "需要token",
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "昵称修改成功",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(description = "data数据为：", value = "{\n" +
                                            "  \"code\": 2000,\n" +
                                            "  \"message\": \"修改成功！\",\n" +
                                            "  \"data\": {\n" +
                                            "    \"user\": {\n" +
                                            "      \"password\": \"77777777\",\n" +
                                            "    },\n" +
                                            "  }\n" +
                                            "}")
                            )),
                    @ApiResponse(responseCode = "2001", description = "密码修改失败")
            })
    public Message rePass(@RequestBody SigIn user, HttpServletRequest request) {
        Message message = new Message();
        String tokenUserId = TokenTool.getTokenUserId(request);
//        修改用户的密码
        int i = userServer.updataPassInId(tokenUserId, user.getPassword());
        if (i == 0) {
//            修改失败
            message.setErrorMessage("密码修改失败！").setCode(3);
            return message;
        }
        message.setSuccessMessage("密码修改成功");
        return message;
    }

    /**
     * 修改头像的接口
     *
     * @param file 要修改的图片 ,
     * @return 返回上传成功后图片的路径地址
     */
    @PostMapping("/uploadimage")
    @ResponseBody
    @Operation(summary = "用户修改头像的方法",
            description = "需要token",
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "修改成功",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(description = "data数据为：", value = "{\n" +
                                            "  \"code\": 2000,\n" +
                                            "  \"message\": \"修改成功！\",\n" +
                                            "  \"data\": {\n" +
                                            "    \"user\": {\n" +
                                            "      \"userid\": 1311111111\n" +
                                            "      \"userpassword\": \"77777777\",\n" +
                                            "    },\n" +
                                            "  }\n" +
                                            "}")
                            )),
                    @ApiResponse(responseCode = "2001", description = "请求错误")
            })
    public String uploadimage(HttpServletRequest request, @RequestParam("alterimage") MultipartFile file) {
//        获取请求的用户
        String tokenUserId = TokenTool.getTokenUserId(request);

        System.out.println("zhanghao1:" + tokenUserId);
//        获取static 目录
        String filePath = ClassUtils.getDefaultClassLoader().getResource("static/").getPath();
        System.out.println("保存的路径的地址 : " + filePath);
//在static目录下创建image目录
        File home = new File(filePath + "upload");
        if (!home.exists()) {
            home.mkdirs();
        }
        String fileName = file.getOriginalFilename();  // 文件名

        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        // 获取上传文件的名称
//        指定文件的新的名字 ,是当前时间 , 加上后缀名
//        fileName = new Date().getTime() + suffixName;
        fileName = tokenUserId + suffixName;
        File dest = new File(home, fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String urlpath = Tool.getDomain() + "/upload/" + fileName;
//        把头像 , 保存起来 ,
        userServer.updataAvaterInId(tokenUserId, urlpath);
//        把头像 , 保存起来 ,
//        把头像的路径 , 返回到对应的客户端
        return urlpath;
    }


    @ResponseBody
    @RequestMapping("/test1")
    public String test1() {
        return "进来了 . test1";
    }

}
